class AutofireFileGenerator

  def	self.initializeXSLT(transition, update = false)
    @transition = transition

    return if !update && File.exists?(transition.xslt_path)

    #in case transition has only ONE incoming place
    #and no xslt is specified (NOP Transition)
    #forward value of incoming token to outgoing places (UGLY!)
    if (!transition.xslt_url && transition.incoming_places.size == 1)
      create_xslt('xslt/cp_one_token.xsl')
    end		
    if transition.xslt_url
      create_xslt(@transition.xslt_url)
    end
  end	


  def self.initializeXML(transition, update = false)
    @transition = transition

    return if !update && File.exists?(transition.xml_path)
    create_xml
  end


  def self.create_token_files(tokens, store_path)
    tokens.each do |token|
      path = File.join(store_path, 'token' + token.place.pid.to_s + '.xml')
      FileGenerator.store_file(token.value, path)
      Merb.logger.info("Automatically saved token xml from place " + token.place.id.to_s + " to " + path)
    end		
  end


  private

  def self.create_xml
    b = binding

    path = @transition.base_path

    incoming_places = @transition.incoming_places

    xml = File.open('xslt/token_file.rhtml').read.gsub(/^  /, '')
    xml_erb = ERB.new(xml, 0, "%<>")

    #store xml to local filesystem
    FileGenerator.store_file(xml_erb.result(b), @transition.xml_path)
  end


  def self.create_xslt(uri)
    return unless uri
    b = binding

    used_names = [@transition.xml_path, @transition.xslt_path]
    path_hash = FileGenerator.locate_and_store_includes(uri, @transition.base_path, used_names)

    local_xslt_url = path_hash[uri].split('/').last

    xslt = File.open('xslt/pnengine.rhtml').read.gsub(/^  /, '')
    xslt_erb = ERB.new(xslt, 0, "%<>")

    #store xslt to local filesystem
    FileGenerator.store_file(xslt_erb.result(b), @transition.xslt_path)
  end		
end
